package com.example.springbootdemo2023.bus.file.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.recorder.FileRecorder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springbootdemo2023.bus.file.dto.File;
import com.example.springbootdemo2023.bus.file.mapper.FileMapper;
import com.example.springbootdemo2023.bus.file.service.IFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 文件记录表 服务实现类
 * </p>
 *
 * @author GaoJingBo
 * @since 2023-04-03
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements IFileService, FileRecorder {


    @SneakyThrows
    @Override
    public boolean record(FileInfo info) {

        File detail = BeanUtil.copyProperties(info, File.class, "attr");

        //这是手动获 取附加属性字典 并转成 json 字符串，方便存储在数据库中
        if (info.getAttr() != null) {
            detail.setAttr(new ObjectMapper().writeValueAsString(info.getAttr()));
        }
        boolean b = save(detail);
        if (b) {
            info.setId(detail.getId());
        }
        return b;
    }

    @SneakyThrows
    @Override
    public FileInfo getByUrl(String url) {

        File detail = getOne(new QueryWrapper<File>().eq("url", url));
        FileInfo info = BeanUtil.copyProperties(detail, FileInfo.class, "attr");

        //这是手动获取数据库中的 json 字符串 并转成 附加属性字典，方便使用
//        if (StrUtil.isNotBlank(detail.getAttr())) {
//            info.setAttr(new ObjectMapper().readValue(detail.getAttr(),Dict.class));
//        }
        return info;
    }

    @Override
    public boolean delete(String url) {
        return remove(new QueryWrapper<File>().eq("url",url));
    }
}
